package com.banciyuan.bcywebview.biz.post.pic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.util.LruCache;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.biz.write.write.WriteHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by squall on 2015/12/30.
 */
public class PostImgAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_IMG = 0;
    private static final int TYPE_PLUS = 1;

    List<PhotoModel> slist = new ArrayList<>();
    LruCache<String, Bitmap> map = new LruCache<>(9);
    Context mContext;
    LayoutInflater inflater;
    private BeforeOpenAlbum beforeOpenAlbum;

    public interface BeforeOpenAlbum {
        void beforeOpen();
    }

    public PostImgAdapter(List<PhotoModel> slist, Context mContext, BeforeOpenAlbum beforeOpenAlbum) {
        this.slist = slist;
        this.beforeOpenAlbum = beforeOpenAlbum;
        this.mContext = mContext;
        this.inflater = LayoutInflater.from(mContext);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_IMG) {
            return new ImageHolder(inflater.inflate(R.layout.post_img_item_exactly, null));
        } else {
            return new PlusHolder(inflater.inflate(R.layout.post_img_item_exactly, null));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_IMG) {
            ImageHolder imageHolder = (ImageHolder) holder;
            setImage(imageHolder, position);
        } else {
            PlusHolder plusHolder = (PlusHolder) holder;
            setPlus(plusHolder);
        }
    }

    @Override
    public int getItemCount() {
        if (slist.size() >= 0 && slist.size() < 9) return slist.size() + 1;
        else return slist.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (slist.size() >= 0 && slist.size() < 9) {
            if (position == slist.size()) {
                return TYPE_PLUS;
            } else {
                return TYPE_IMG;
            }
        } else {
            return TYPE_IMG;
        }
    }

    private class ImageHolder extends RecyclerView.ViewHolder {
        ImageView img_content;
        ImageView img_cancel;
        TextView progress;

        public ImageHolder(View convertView) {
            super(convertView);
            img_content = (ImageView) convertView.findViewById(R.id.item_group_content);
            img_cancel = (ImageView) convertView.findViewById(R.id.item_group_cancel);
            progress = (TextView) convertView.findViewById(R.id.progress_bar);
        }
    }

    private class PlusHolder extends RecyclerView.ViewHolder {
        ImageView img_content;
        ImageView img_cancel;
        TextView progress;

        public PlusHolder(View convertView) {
            super(convertView);
            img_content = (ImageView) convertView.findViewById(R.id.item_group_content);
            img_cancel = (ImageView) convertView.findViewById(R.id.item_group_cancel);
            progress = (TextView) convertView.findViewById(R.id.progress_bar);
        }
    }

    private void setPlus(final PlusHolder plusHolder) {
        plusHolder.img_content.setImageDrawable(mContext.getResources().getDrawable(R.drawable.publish_add));
        plusHolder.img_cancel.setVisibility(View.GONE);
        plusHolder.progress.setVisibility(View.GONE);
        plusHolder.img_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getAlbumPic();
            }
        });
    }

    private void setImage(final ImageHolder imageHolder, final int position) {
        if (position < slist.size()) {
            if (map.get(slist.get(position).getOriginalPath()) == null) {
                new AsyncTask<Void, Bitmap, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(Void... params) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;
                        if (!slist.isEmpty() && position < slist.size())
                            return BitmapFactory.decodeFile(slist.get(position).getOriginalPath(), options);
                        else
                            return null;
                    }

                    @Override
                    protected void onPostExecute(Bitmap bitmap) {
                        if (bitmap != null) {
                            if (!slist.isEmpty() && position < slist.size()) {
                                map.put(slist.get(position).getOriginalPath(), bitmap);
                                imageHolder.img_content.setImageBitmap(bitmap);
                                setProgress(slist.get(position), imageHolder);
                            }
                        }
                    }
                }.execute();
            } else {
                imageHolder.img_content.setImageBitmap(map.get(slist.get(position).getOriginalPath()));
                setProgress(slist.get(position), imageHolder);
            }
            imageHolder.img_cancel.setVisibility(View.VISIBLE);
            imageHolder.img_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
                    alphaAnimation.setDuration(200);
                    ((View) (view.getParent())).startAnimation(alphaAnimation);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (!slist.isEmpty() && position < slist.size()) {
                                slist.remove(position);
                            }
                            PostImgAdapter.this.notifyDataSetChanged();
                        }
                    }, alphaAnimation.getDuration());
                }
            });
            imageHolder.img_content.setOnClickListener(null);
        }
    }

    private void getAlbumPic() {
        beforeOpenAlbum.beforeOpen();
        Intent intent = new Intent(mContext, PhotoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("photos", (Serializable) slist);
        intent.putExtras(bundle);
        ((Activity) mContext).startActivityForResult(intent, WriteHelper.PICK_IMAGE);
    }

    private void setProgress(PhotoModel p, ImageHolder imageHolder) {
        if (!p.isfail()) {
            if (!p.isUpload()) {
                imageHolder.progress.setVisibility(View.VISIBLE);
                imageHolder.progress.setText(String.valueOf((int) (p.getProgress() * 100)) + "%");
            } else {
                imageHolder.progress.setVisibility(View.GONE);
            }
        } else {
            imageHolder.progress.setText(mContext.getString(R.string.upload_fail_retry));
        }
    }

}
